package com.wang.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.auth.mapper.ProcessMapper;
import com.wang.auth.service.*;
import com.wang.common.result.Result;
import com.wang.model.process.Process;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.model.process.ProcessRecord;
import com.wang.model.process.ProcessTemplate;
import com.wang.model.process.dto.ProcessDto;
import com.wang.model.process.vo.ApprovalVo;
import com.wang.model.process.vo.ProcessFormVo;
import com.wang.model.process.vo.ProcessQueryVo;
import com.wang.model.system.SysUser;
import com.wang.security.custom.LoginInfoHelper;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.*;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.*;
import java.util.zip.ZipInputStream;

/**
 * <p>
 * 审批类型 服务实现类
 * </p>
 *
 * @author wang
 * @since 2023-04-17
 */
@Service
@Slf4j
public class ProcessServiceImpl extends ServiceImpl<ProcessMapper, Process> implements ProcessService {

    @Resource
    ProcessMapper processMapper;

    @Resource
    RepositoryService repositoryService;

    @Resource
    SysUserService userService;

    @Resource
    RuntimeService runtimeService;

    @Resource
    ProcessTypeService processTypeService;

    @Resource
    ProcessTemplateService processTemplateService;

    @Resource
    TaskService taskService;

    @Resource
    ProcessRecordService processRecordService;

    @Resource
    HistoryService historyService;

    @Override
    public Page<ProcessDto> selectPage(Page<Process> page, ProcessQueryVo processQueryVo) {
        Page<ProcessDto> processDtoPage = processMapper.queryPage(page, processQueryVo);
        List<ProcessDto> records = processDtoPage.getRecords();
        records.forEach(System.out::println);
        return processDtoPage;
    }

    //部署流程定义
    @Override
    public void deployByZip(String deployPath) {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(deployPath);
        System.out.println(inputStream.toString());
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        //部署
        Deployment deploy = repositoryService.createDeployment().addZipInputStream(zipInputStream).deploy();
        System.out.println(deploy.toString());
    }

    @Override
    public Result startUp(ProcessFormVo processFormVo) {
        //1.根据当前用户id获取用户信息
        ThreadLocal<Long> userId = LoginInfoHelper.getUserId();
        SysUser user = userService.getById(userId.get());
        //2.根据审批模板id把模板信息查询
        ProcessTemplate processTemplate = processTemplateService.getById(processFormVo.getProcessTemplateId());
        //3.保存提交审批信息到业务表 oa_process
        Process process = new Process();
        BeanUtils.copyProperties(processFormVo,process);
        process.setProcessCode(System.currentTimeMillis()+"");
        process.setUserId(userId.get());
        process.setStatus(1);
        process.setTitle(user.getName()+"发起"+processTemplate.getName()+"申请");
        baseMapper.insert(process);
        //启动流程实例 - RuntimeService
        //流程定义Key
        String processDefinitionKey = processTemplate.getProcessDefinitionKey();
        //业务Key processId
        String processKey = String.valueOf(process.getId());
        //流程参数form表单json数据转换为map集合
        String formValues = processFormVo.getFormValues();
        JSONObject jsonObject = JSON.parseObject(formValues);
        JSONObject formShowData = jsonObject.getJSONObject("formShowData");
        //遍历formShowData，得到里面的内容封装成map集合，JSONObject本身也是类似于map集合的，也是由键值对构成
        Map<String, Object> map = new HashMap<>(formShowData);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("data",map);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, processKey, dataMap);
        
        //查询下一个审批人
        //审批人可以有多个
        List<Task> taskList = this.getCurrentTaskList(processInstance.getId());
        List<String> names = new ArrayList<>();
        for (Task task : taskList) {
            String assigneeName = task.getAssignee();
            SysUser userByUserName = userService.getUserByUserName(assigneeName);
            String name = userByUserName.getName();
            names.add(name);
            //推送消息

        }
        process.setProcessInstanceId(processInstance.getId());
        process.setDescription("等待" + StringUtils.join(names.toArray(), "，") + "审批");
        //业务和流程关联，更新oa_process数据
        int i = baseMapper.updateById(process);
        processRecordService.record(process.getId(),1,"发起申请");
        return Result.success(i > 0 ? "提交成功！" : "提交失败");
    }

    //查询待处理任务列表
    @Override
    public Page<ProcessDto> findPending(Page<Process> pageProcess) {
        //1封装查询条件，根据当前用户名
        TaskQuery query = taskService.createTaskQuery().taskAssignee(LoginInfoHelper.getUsername().get()).orderByTaskCreateTime().desc();
        //调用方法分页查询，返回list集合，待办任务集合
        int begin = (int) ((pageProcess.getCurrent() - 1) * pageProcess.getSize());
        int size = (int) pageProcess.getSize();
        List<Task> taskList = query.listPage(begin, size);
        //封装返回list集合数据到Dto集合中
        List<ProcessDto> processDtoList = new ArrayList<>();
        for (Task task : taskList) {
            //从task中获取流程实例id
            String processInstanceId = task.getProcessInstanceId();
            //根据流程实例id获取流程实例对象
            ProcessInstance processInstance = runtimeService
                    .createProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            //从流程实例对象中获取业务key
            Long businessKey = Long.valueOf(processInstance.getBusinessKey());
            //根据业务key获取Process对象
            Process process = baseMapper.selectById(businessKey);
            //将Process复制给ProcessDto
            ProcessDto processDto = new ProcessDto();
            BeanUtils.copyProperties(process,processDto);
            processDto.setTaskId(task.getId());
            processDtoList.add(processDto);
        }

        //封装返回Page对象,query.count()是总记录数
        Page<ProcessDto> processDtoPage = new Page<>(pageProcess.getCurrent(),pageProcess.getSize(),query.count());
        return processDtoPage.setRecords(processDtoList);
    }

    @Override
    public Map<String, Object> show(Long id) {
        //1.根据流程id获取流程信息Process
        Process process = baseMapper.selectById(id);
        //2.根据流程id获取流程记录信息
        LambdaQueryWrapper<ProcessRecord> processRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        processRecordLambdaQueryWrapper.eq(ProcessRecord::getProcessId,id);
        List<ProcessRecord> processRecordList = processRecordService.list(processRecordLambdaQueryWrapper);
        //3.根据模板id查询模板信息
        ProcessTemplate processTemplate = processTemplateService.getById(process.getProcessTemplateId());
        //4.判断用户是否可以审批
        //可以看到信息的人不一定能审批，不能重复审批
        boolean isApprove = false;
        List<Task> currentTaskList = this.getCurrentTaskList(process.getProcessInstanceId());
        for (Task task : currentTaskList) {
            //判断任务人是否是当前用户
            String username = LoginInfoHelper.getUsername().get();
            if (task.getAssignee().equals(username)){
                isApprove = true;
            }
        }
        //5.查询数据封装到map集合，返回
        HashMap<String, Object> map = new HashMap<>();
        map.put("process",process);
        map.put("processRecordList",processRecordList);
        map.put("processTemplate",processTemplate);
        map.put("isApprove",isApprove);
        return map;
    }

    @Override
    public void approve(ApprovalVo approvalVo) {
        //1.从approvalVo获取任务id，根据id获取流程变量
        String taskId = approvalVo.getTaskId();
        Map<String, Object> variables = taskService.getVariables(taskId);
        for (Map.Entry<String,Object> entry:variables.entrySet()){
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }
        Long processId = approvalVo.getProcessId();
        //2.判断审批状态值 状态值=1，审批通过
        Integer status = approvalVo.getStatus();
        if (status == 1){
            HashMap<String, Object> map = new HashMap<>();
            taskService.complete(taskId);
        }else {
            //状态值等于-1，驳回，流程结束
            this.endTask(taskId);
        }

        //记录审批过程信息 oa_process_record
        String description = status == 1 ? "已通过" : "驳回";
        processRecordService.record(processId,status,description);

        //查询下一个审批人，更新流程表记录
        Process process = baseMapper.selectById(processId);
        //查询任务
        List<Task> currentTaskList = this.getCurrentTaskList(process.getProcessInstanceId());
        if (!CollectionUtils.isEmpty(currentTaskList)){
            ArrayList<String> assignList = new ArrayList<>();
            for (Task task : currentTaskList) {
                String assignee = task.getAssignee();
                SysUser userByUserName = userService.getUserByUserName(assignee);
                assignList.add(userByUserName.getName());
                //TODO
            }
            //更新process流程信息
            process.setDescription("等待" + StringUtils.join(assignList.toArray(),",")+"审批");
            process.setStatus(1);
        } else {
            if (approvalVo.getStatus() == 1){
                process.setDescription("审批通过");
                process.setStatus(2);
            } else {
                process.setDescription("驳回");
                process.setStatus(-1);
            }
        }
        baseMapper.updateById(process);
    }

    @Override
    public IPage<ProcessDto> findProcessed(Page<Process> processPage) {
        //封装查询条件
        HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(LoginInfoHelper.getUsername().get())
                .finished()
                .orderByTaskCreateTime()
                .desc();
        //调用方法条件分页查询，返回list集合
        //开始位置，和 每页显示记录数
        int begin = (int) ((processPage.getCurrent() - 1) * processPage.getSize());
        int size = (int) processPage.getSize();
        List<HistoricTaskInstance> historicTaskInstances = query.listPage(begin, size);
        long count = query.count();

        //遍历返回list集合，封装List<ProcessDto>
        ArrayList<ProcessDto> processDtoList = new ArrayList<>();
        for (HistoricTaskInstance historicTaskInstance : historicTaskInstances) {
            //获取流程实例的id
            String processInstanceId = historicTaskInstance.getProcessInstanceId();
            //根据流程实例id查询process信息
            LambdaQueryWrapper<Process> processLambdaQueryWrapper = new LambdaQueryWrapper<>();
            processLambdaQueryWrapper.eq(Process::getProcessInstanceId,processInstanceId);
            Process process = baseMapper.selectOne(processLambdaQueryWrapper);
            ProcessDto processDto = new ProcessDto();
            BeanUtils.copyProperties(process,processDto);
            processDtoList.add(processDto);
        }
        //IPage封装分页查询所有数据
        IPage<ProcessDto> processDtoPage = new Page<>(processPage.getCurrent(),processPage.getSize());
        processDtoPage.setRecords(processDtoList);
        return processDtoPage;
    }

    @Override
    public IPage<ProcessDto> findStarted(Page<Process> pageParam) {
        ProcessQueryVo processQueryVo = new ProcessQueryVo();
        processQueryVo.setUserId(LoginInfoHelper.getUserId().get());
        IPage<ProcessDto> pageModel = baseMapper.queryPage(pageParam, processQueryVo);
        for (ProcessDto item : pageModel.getRecords()) {
            item.setTaskId("0");
        }
        return pageModel;
    }

    //结束流程
    private void endTask(String taskId) {
        //1.根据任务id获取任务对象Task
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //2.获取流程定义模型BpmnModel
        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
        //3.获取结束流向结点
        List<EndEvent> endEventList = bpmnModel.getMainProcess().findFlowElementsOfType(EndEvent.class);
        if (CollectionUtils.isEmpty(endEventList)){
            return;
        }
        FlowNode endEvent = endEventList.get(0);

        //当前流向结点
        FlowNode flowElement = (FlowNode) bpmnModel.getMainProcess().getFlowElement(task.getTaskDefinitionKey());

        //临时保存当前活动的原始方向
        List<List<SequenceFlow>> objectArrayList = new ArrayList<>();
        objectArrayList.add(flowElement.getOutgoingFlows());
        //清理当前流动的方向
        flowElement.getOutgoingFlows().clear();

        //6.创建新流向
        SequenceFlow sequenceFlow = new SequenceFlow();
        sequenceFlow.setId("sequenceFlow");
        sequenceFlow.setSourceFlowElement(flowElement);
        sequenceFlow.setTargetFlowElement(endEvent);
        //7.当前结点指向新方向
        ArrayList<SequenceFlow> newSequenceFlowList = new ArrayList<>();
        newSequenceFlowList.add(sequenceFlow);
        flowElement.setOutgoingFlows(newSequenceFlowList);
        //8.完成当前任务
        taskService.complete(taskId);
    }

    //当前任务的列表
    private List<Task> getCurrentTaskList(String id) {
        return taskService.createTaskQuery().processInstanceId(id).list();
    }
}
